package com.bardsoftware.foronuvolo.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.cache.Cache;

import com.bardsoftware.foronuvolo.data.FeedItem;

public class MessageCache<K, V> {
    private final Cache myCache;
    private final String myPrefix;
    private boolean isVersioned;

    public MessageCache(Cache cache, String prefix) {
        myCache = cache;
        myPrefix = prefix;
    }
    public V get(K key) {
        if (myCache == null) {
            return null;
        }
        String cacheKey = createCacheKey(key);
        return (V) myCache.get(cacheKey);
    }
    public void put(K key, V value) {
        if (myCache == null) {
            return;
        }
        String cacheKey = createCacheKey(key);
        myCache.put(cacheKey, value);
    }

    public void setVersioned(boolean b) {
        isVersioned = b;
    }
    public void reset() {
        if (myCache != null) {
            incrementVersion();
        }
    }

    private String createCacheKey(K key) {
        if (!isVersioned) {
            return myPrefix + "_" + key.toString();
        }
        String version = (String) myCache.get(myPrefix + "V");
        if (version == null) {
            version = incrementVersion();
        }
        return myPrefix + version + "_" + key.toString();
    }
    private String incrementVersion() {
        String ts = FeedItem.DATE_FORMAT.format(new Date());
        myCache.put(myPrefix + "V", ts);
        return ts;
    }

    private static List<MessageCache> ourDiscussionCaches = new ArrayList<MessageCache>();

    static void onDiscussionSetChange() {
        for (MessageCache cache : ourDiscussionCaches) {
            cache.reset();
        }
    }

    static void addDiscussionCache(MessageCache cache) {
        ourDiscussionCaches.add(cache);
    }
}
